package com.tg.sieve_data.controller.sys;

import com.tg.sieve_data.common.Result;
import com.tg.sieve_data.entity.sys.SysUserEntity;
import com.tg.sieve_data.service.sys.SysUserService;
import com.tg.sieve_data.service.sys.SysUserTokenService;
import com.tg.sieve_data.vo.SysLoginForm;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * 登录相关
 *
 */
@RestController
public class SysLoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return Result.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return Result.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		Result r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}


	/**
	 * 退出
	 */
	@GetMapping("/sys/logout")
	public Result logout() {
		Long userId= UserIdHolder.getUserId();
		if (Objects.isNull(userId)) {
			return Result.error("用户未登录");
		}
		sysUserTokenService.logout(userId);
		return Result.success();
	}

}
